package com.example.excel.resolve;

import com.example.excel.format.CellValueFormatListener;
import com.example.excel.pojo.BaseExcel;
import com.example.excel.pojo.BaseRow;
import com.example.excel.pojo.BaseSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public abstract class AbsExcelResolveTemplate<T> implements ExcelResolveEachListener<T>{

    private CellValueFormatListener formatListener;

    private BaseExcel<T> excelData = new BaseExcel<>();
    private BaseSheet<T> tempSheet;
    private BaseRow<T> tempRow;

    abstract boolean isResolveSheet(BaseSheet<T> baseSheet);

    abstract boolean isResolveRow(int rowNum, Row row);

    abstract T newInstanceRow(BaseRow<T> baseRow, Row row);

    abstract void resolveCell(BaseRow<T> baseRow, int cellNum, Cell cell, T data);

    @Override
    public boolean resolveSheet(int sheetIndex, Sheet sheet) {
        tempSheet = excelData.createSheet(sheetIndex, sheet.getSheetName());
        return isResolveSheet(tempSheet);
    }

    @Override
    public boolean resolveRow(int rowNum, Row row) {
        if(isResolveRow(rowNum, row)){
            tempRow = tempSheet.createRow(rowNum);
            tempRow.setRowData(newInstanceRow(tempRow, row));
            return true;
        }
        return false;
    }

    @Override
    public void resolve(int sheetIndex, int rowNum, int cellNum, Cell cell) {
        resolveCell(tempRow, cellNum, cell, tempRow.getRowData());
    }

    @Override
    public void setFormatListener(CellValueFormatListener formatListener) {
        this.formatListener = formatListener;
    }

    @Override
    public BaseExcel<T> getResult() {
        return excelData;
    }

    @Override
    public void clear() {
        formatListener = null;
    }

    public CellValueFormatListener getFormatListener() {
        if(formatListener==null){
            formatListener = new CellValueFormatListener.CellValueFormat();
        }
        return formatListener;
    }

    <K> K formatValue(Cell cell, Class<K> typeClass){
        return getFormatListener().formatValue(cell, typeClass);
    }
}
